// 获取数据库所有表信息
'use api/dm/sql/formatCondition.js'
function getTablesInfoStmt() {
    const placeholdersObj = formatCondition();
    const newPlaceholders = placeholdersObj.placeholders;
    if (newPlaceholders != '') {
        const tempParams = placeholdersObj.tempParams;
        return {
            query: `SELECT TABLE_NAME, TABLE_COMMENT, TABLE_ROWS, CREATE_TIME, UPDATE_TIME  FROM information_schema.tables WHERE TABLE_SCHEMA  = DATABASE() AND ${newPlaceholders} LIMIT ?,?;`,
            params: [...tempParams, (params.pageNum - 1) * params.pageSize, params.pageSize],
        };
    } else {
        return {
            query: `SELECT TABLE_NAME, TABLE_COMMENT, TABLE_ROWS, CREATE_TIME, UPDATE_TIME  FROM information_schema.tables WHERE TABLE_SCHEMA  = DATABASE() LIMIT ?,?`,
            params: [(params.pageNum - 1) * params.pageSize, params.pageSize],
        };
    }
}

// 列表查询总数据
function genCountTotal() {
    const placeholdersObj = formatCondition();
    const newPlaceholders = placeholdersObj.placeholders;
    if (newPlaceholders != '') {
        const tempParams = placeholdersObj.tempParams;
        return {
            query: `SELECT COUNT(*) AS count FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE() AND ${newPlaceholders}`,
            params: [...tempParams],
        };
    } else {
        return {
            query: `SELECT COUNT(*) AS count FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()`,
            params: [],
        };
    }
}

function getTablesInfo() {
    let stmt = getTablesInfoStmt()
    let countQuery = genCountTotal()
    var dataRes = SQL.query(DB_NAME, stmt.query, ...stmt.params)
    var countRes = SQL.query(DB_NAME, countQuery.query, ...countQuery.params)
    if (dataRes) {
        return { result: dataRes, count: Number(countRes[0]?.count) }
    }
    return undefined
}

function isExistTable() {
    var result = SQL.query(DB_NAME, `SELECT 1 FROM information_schema.tables WHERE TABLE_SCHEMA  = DATABASE() AND TABLE_NAME = ?`, TABLE_NAME)
    return result && result.length
}

function getTableInfo() {
    let isExist = isExistTable()
    if (isExist) {
        var result = SQL.query(DB_NAME, `SELECT TABLE_NAME, TABLE_COMMENT, TABLE_ROWS, CREATE_TIME, UPDATE_TIME  FROM information_schema.tables WHERE TABLE_SCHEMA  = DATABASE() AND TABLE_NAME = ?`, TABLE_NAME)
        if (result) {
            return result
        }
    }
    return undefined
}

function getTableCollums() {
    let isExist = isExistTable()
    if (isExist) {
        var result = SQL.query(DB_NAME, `SHOW FULL COLUMNS FROM ${TABLE_NAME};`)
        if (result) {
            return result
        }
    }
    return undefined
}